package com.oa.web.controller;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.config.AlibabaMainConfig;
import com.alipay.config.AlipayClientFactory;

@Controller
@RequestMapping("/skynetPay")
public class SkynetPayController {
    private static Logger logger = Logger.getLogger(SkynetPayController.class);
    //@ApiOperation(value = "请求支付宝构造订单数据", notes = "请求支付宝构造订单数据")
    @RequestMapping(value = "/alibabaOrdPrePay", method = RequestMethod.GET)
    @ResponseBody
    public void alibabaOrdPrePay(
            @RequestParam(value = "ordCd", required = true) String ordCd,
            @RequestParam(value = "coupCd", required = true) String coupCd,
            @RequestParam(value = "openId", required = true)String openId,
            HttpServletResponse response,HttpServletRequest request) {
        try {
            //支付请求前的数据处理
 
            // 参数目前都是 写死的 根据业务需求 写活
            Map<String, String> maps = new HashMap<String, String>();
            maps.put("out_trade_no", ordCd);
            // 付款金额，必填
            maps.put("total_amount", "0.01");
            // 订单名称，必填
            maps.put("subject", "测试订单名");
            // 商品描述，可空
            maps.put("body", "商品描述");
            // 销售产品码 必填
            maps.put("product_code", "QUICK_WAP_PAY");
            // 超时时间 可空
            maps.put("timeout_express", "2m");
            maps.put("passback_params", URLEncoder.encode(openId, "UTF-8"));
            try {
                AlipayClientFactory ali = new AlipayClientFactory();
                String form = ali.ydAndPc_Pay(maps);
//                logger.info("预请求返回数据：" + form);
                if (!form.equals("err")) {
                    response.setContentType("text/html;charset=" + AlibabaMainConfig.CHARSET);
                    response.getWriter().write(form);// 直接将完整的表单html输出到页面
                    response.getWriter().flush();
                    response.getWriter().close();
                } else {
//                    logger.info("请求失败，请重试！");
                }
            } catch (AlipayApiException e) {
                e.printStackTrace();
//                logger.info(e);
            }
        } catch (Throwable t) {
//            logger("支付宝支付失败"+t);
        }
    }
    //@ApiOperation(value = "支付宝支付回调", notes = "支付宝支付回调")
    @RequestMapping(value = "/notifyCallBack")
    public void notifyCallBack(HttpServletRequest request, HttpServletResponse response) {
        try {
            logger.info("收到支付成功异步接到消息通知,开始处理");
            Map<String, String> params = new HashMap<String, String>();
            Map<String,String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = iter.next();
                String[] values = requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
                }
                // 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
                // valueStr = new String(valueStr.getBytes("ISO-8859-1"),
                // "gbk");
                params.put(name, valueStr);
            }
            logger.info("支付成功异步接到消息通知，参数：" + params.toString());
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
            // 计算得出通知验证结果
            // //boolean AlipaySignature.rsaCheckV1(Map<String, String> params,
            // String publicKey, String charset, String sign_type)
            boolean verify_result = AlipaySignature.rsaCheckV1(params, AlibabaMainConfig.ALIPAY_PUBLIC_KEY,
                    AlibabaMainConfig.CHARSET, AlibabaMainConfig.SIGNTYPE);
            if (verify_result) {
                // 验证成功
                // 请在这里加上商户的业务逻辑程序代码
                if (trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")) {
                    // 支付宝订单号,先判断该笔订单是否处理过，如果处理过，则直接返回
                    //这里写能正确收到返回数据的处理逻辑
                }
                response.getWriter().println("success"); // 请不要修改或删除
            } else {
                // 验证失败
                response.getWriter().println("fail");
            }
            response.getWriter().flush();
        } catch (Throwable t) {
            logger.info("阿里支付回调异常", t);
            try {
                response.getWriter().println("fail");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
/*
<form name="punchout_form" method="post" action="https://openapi.alipay.com/gateway.do?sign=Sbz0dOouIC8WtgZLwqpuZ4osdK3wiIBhqgb6WiXfvtfGid2iU0LuM9MAjU8MZ3YNZGZikxZJlOlou0yV7REYCBfkJ9zRo48AAZWjcy3xbMWASIVWfBpbgULXB3KgMSKOKu8DraLmrvYFgAfoU%2Bz8NQifpmYk2Ew68BjRsfIFTMtgTDGNGvWf6OYEL8OBzKXH3Ehg4liZlRwk6Y9G1UOabSx5TKsYERMuMGN71JYQCBpS9FpCMJ%2F9J3OFYZ9hPIWkBAX6vcq9dxZsJunsM%2F3hP3XOmpqbINoEIOTxiq1ueWOGklvryjB0kc1L06EIADceGKzRgAxEJpVDxJm9zpV%2Fxg%3D%3D×tamp=2017-08-15+15%3A58%3A38&sign_type=RSA2¬ify_url=http%3A%2F%2Fwww.dong-ai.com%2Fwx%2Fbss%2FalibabaPay%2FnotifyCallBack&charset=UTF-8&app_id=2017051807272022&method=alipay.trade.wap.pay&return_url=http%3A%2F%2Fwww.dong-ai.com%2Fwx%2Fpage%2Falibaba%2Freturn_url.jsp&version=1.0&alipay_sdk=alipay-sdk-java-dynamicVersionNo&format=json">
<input type="hidden" name="biz_content" value="{"total_amount":"0.01","body":" 商品描述","timeout_express":"2m","product_code":"QUICK_WAP_PAY","subject":" 测试订单名","passback_params":"oKUhX1iuVlThnpYZxG6ldgyUMgVU","out_trade_no":"170804193400302247"}">
<input type="submit" value="立即支付" style="display:none" >
</form>
<script>document.forms[0].submit();</script>
*/
